package com.zhijiaoyun.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhijiaoyun.common.DsConstant;
import com.zhijiaoyun.common.ResponseUtils;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.dao.ILessonDao;
import com.zhijiaoyun.model.BuyHistory;
import com.zhijiaoyun.model.Course;
import com.zhijiaoyun.model.Lesson;
import com.zhijiaoyun.model.dto.PageData;
import com.zhijiaoyun.model.dto.PageList;
import com.zhijiaoyun.service.IBuyHistoryService;
import com.zhijiaoyun.service.ICourseService;
import com.zhijiaoyun.service.ILessonService;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Service(value = "lessonService")
public class LessonServiceImpl implements ILessonService {

    @Resource
    ILessonDao lessonDao;

    @Autowired
    IBuyHistoryService buyHistoryService;

    @Autowired
    ICourseService courseService;

    @Override
    public Lesson getLessonByName(String name) {
        return lessonDao.selectByName(name);
    }

    @Override
    public Map<String, Object> addLesson(Lesson lesson) {
        Course course = courseService.getCourseByCourseId(lesson.getCourseId());
        if (course == null) {
            return ResponseUtils.responseCourseLost();
        }

        Lesson lesson1 = getLessonByNameCourseId(lesson.getCourseId(), lesson.getName());
        if (lesson1 != null) {
            return ResponseUtils.responseErrorMap(DsConstant.CODE_LESSON_NAME_EXIST, DsConstant.MESSAGE_LESSON_NAME_EXIST);
        }
        List<Lesson> lessonList = getLessonByCourseId(lesson.getCourseId());
        if (StringUtils.isNotEmptyList(lessonList)) {
            lesson.setSort(lessonList.get(lessonList.size() - 1).getSort() + 1);
        }

        lessonDao.insert(lesson);

        // 课程上的课时数加1（实时查询添加）
        courseService.changeLessonNum(lesson.getCourseId());
        return ResponseUtils.responseSuccessMap();
    }

    @Override
    public Lesson getLessonByLessonId(Long lessonId) {
        return lessonDao.selectByPrimaryKey(lessonId);
    }

    @Override
    public Lesson getLessonByNameCourseIdNotLessonId(Long lessonId, Long courseId, String name) {
        return lessonDao.selectByNameCourseIdNotLessonId(lessonId, courseId, name);
    }

    @Override
    public Map<String, Object> modifyLesson(Lesson lesson) {
        long lessonId = lesson.getLessonId();
        long courseId = lesson.getCourseId();
        Lesson lessonObj = getLessonByLessonIdCourseId(lessonId, courseId);
        if (lessonObj == null) {
            return ResponseUtils.responseLessonLost();
        }

        if (!StringUtils.isEmptyString(lesson.getName())) {
            Lesson temp = getLessonByNameCourseIdNotLessonId(lessonId, courseId, lesson.getName());
            if (temp != null) {
                return ResponseUtils.responseErrorMap(DsConstant.CODE_LESSON_NAME_EXIST, DsConstant.MESSAGE_LESSON_NAME_EXIST);
            }
            lessonObj.setName(lesson.getName());
        }

        if (!StringUtils.isEmptyString(lesson.getVideoUrl())) {
            lessonObj.setVideoUrl(lesson.getVideoUrl());
        }

        if (!StringUtils.isEmptyString(lesson.getTitle())) {
            lessonObj.setTitle(lesson.getTitle());
        }

        if (lesson.getLessonType() != null) {
            lessonObj.setLessonType(lesson.getLessonType());
        }

        if (!StringUtils.isEmptyString(lesson.getContent())) {
            lessonObj.setContent(lesson.getContent());
        }

        lessonObj.setModifyTime(new Date());
        lessonObj.setModifyUser(lesson.getCreateUser());

        lessonDao.updateByPrimaryKey(lessonObj);
        return ResponseUtils.responseSuccessMap();
    }

    @Override
    public PageList<Lesson> pageByParams(Long courseId, Integer pageIndex, String name, String title) {
        PageList<Lesson> pageList = new PageList<>();
        if (courseId == null) {
            return pageList;
        }

        int count = lessonDao.countByParams(courseId, name, title);
        PageData pageData = new PageData();
        List<Lesson> list = new ArrayList<>();
        if (count > 0) {
            int pageIndexInt = pageIndex == null ? 1 : pageIndex;
            pageData = PageData.createPage(count, pageIndexInt, DsConstant.PAGESIZE_DEFAULT);
            list = lessonDao.pageByParams(pageData.getBeginIndex(), pageData.getPageSize(), courseId, name, title);
            pageList = new PageList<>(list, pageData);
        }
        return pageList;
    }

    @Override
    public Lesson getLessonByNameCourseId(Long courseId, String name) {
        return lessonDao.selectByNameCourseId(courseId, name);
    }

    @Override
    public List<Lesson> getLessonByCourseId(Long courseId) {
        return lessonDao.selectLessonByCourseId(courseId);
    }

    @Override
    public Lesson getLessonByLessonIdCourseId(Long lessonId, Long courseId) {
        return lessonDao.selectByLessonIdCourseId(lessonId, courseId);
    }

    @Override
    public List<Lesson> getByParams(Long courseId, String name, String title) {
        return lessonDao.selectByParams(courseId, name, title);
    }

    @Override
    public void deleteLesson(Lesson lesson) {
        lessonDao.deleteByPrimaryKey(lesson.getLessonId());
    }

    @Override
    public int countAll() {
        return lessonDao.countAll();
    }

    @Override
    public Map<String, Object> getLessonById(Long lessonId) {
        Lesson lesson = getLessonByLessonId(lessonId);
        Map<String, Object> map = new HashMap<>();
        map.put("obj", lesson);
        return ResponseUtils.responseSuccessMap(map);
    }

    @Override
    public Map<String, Object> listByParams(Long courseId, String name, String title) {
        List<Lesson> lessons = getByParams(courseId, name, title);
        Map<String, Object> map = new HashMap<>();
        map.put("list", lessons);
        map.put(DsConstant.CODE, DsConstant.CODE_SUCCESS);
        return ResponseUtils.responseSuccessMap(map);
    }

    @Override
    public Map<String, Object> deleteCourse(Long courseId, Long lessonId) {
        Lesson lesson = getLessonByLessonIdCourseId(lessonId, courseId);
        if (lesson == null) {
            return ResponseUtils.responseLessonLost();
        }
        // 判断有无被购买
        List<BuyHistory> buys = buyHistoryService.getBuyHistoryByGoodsId(1, 1, courseId, 1);
        if (!StringUtils.isEmptyList(buys)) {
            return ResponseUtils.responseErrorMap(DsConstant.CODE_COURSE_DELETE_ERROR_1, "该课程已有人购买，不能删除");
        }
        deleteLesson(lesson);
        courseService.changeLessonNum(courseId);
        return ResponseUtils.responseSuccessMap();
    }

    @Override
    public Map<String, Object> sort(long lessonId, int sort, String createUser) {
        Lesson lesson = getLessonByLessonId(lessonId);
        if (lesson == null) {
            return ResponseUtils.responseLessonLost();
        }

        List<Lesson> lessonList;
        if (sort > lesson.getSort()) {
            // 排序往前靠往后靠，目标sort后面的数据，全部加1
            lessonList = lessonDao.listAfterSort(sort - 1, lesson.getCourseId());
        } else {
            // 排序往前靠，目标sort 到当前sort的数据，全部加1
            lessonList = lessonDao.listBetweenSort(sort + 1, lesson.getSort(), lesson.getCourseId());
        }
        if (StringUtils.isNotEmptyList(lessonList)) {
            lessonDao.updateSort(lessonList, createUser);
        }

        lesson.setSort(sort);
        lessonDao.updateByPrimaryKey(lesson);
        return ResponseUtils.responseSuccessMap();
    }

}
